﻿using DemoApp1.Common;
using DemoApp1.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;

namespace DemoApp1
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AppConfig.Configure();
        }

        public override void Init()
        {
            this.AuthenticateRequest += MvcApplication_AuthenticationRquest;
            this.PostAuthenticateRequest += Application_PostRequestHandlerExecute;
            base.Init();
        }

        void MvcApplication_AuthenticationRquest(object sender, EventArgs e)
        {
            //var issso = Convert.ToBoolean(ConfigurationManager.AppSettings.Get("IsEnabledSSO"));
            //if (!issso)
            //{
            //    return;
            //}
            // IAuthorizeService srvAuthorize = ServiceContainer.Self.Resolve<IAuthorizeService>();
            string requestUrl = HttpContext.Current.Request.RawUrl;
            HttpCookie accessTokenCookie = null;
            if (Context.User != null && Context.User.Identity.IsAuthenticated)
            {
                return;
            }
            accessTokenCookie = HttpContext.Current.Request.Cookies[AppConfig.AccessTokenCookieName];
            //非AJAX请求 AccessToken
            //if (!new HttpContextWrapper(Context).Request.IsAjaxRequest())
            //{
            //    accessTokenCookie = HttpContext.Current.Request.Cookies[ClientConfig.AccessTokenCookieName];
            //}
            //else
            //{ //RefreshToken
            //    accessTokenCookie = HttpContext.Current.Request.Cookies[ClientConfig.RefreshedAccessTokenCookieName];
            //}
            if (accessTokenCookie != null)
            {
                var decryptedAccessTokenTicket = FormsAuthentication.Decrypt(accessTokenCookie.Value);
                if (decryptedAccessTokenTicket != null)
                {
                    var accessToken = decryptedAccessTokenTicket.UserData;
                    RestClientHelp restClientHelp = new RestClientHelp(AppConfig.AuthorizationServerBaseAddress, AppConfig.ResourceServerAPIAddress);

                    //获取用户信息
                    string result = restClientHelp.GetUserData(accessToken);
                    if (!string.IsNullOrWhiteSpace(result) && string.Compare(result, "null", true) != 0)
                    {
                        dynamic user = JObject.Parse(result);
                        CWPrincipal principal = new CWPrincipal();
                        principal.UserID = user.UserID;
                        principal.UserName = user.UserName;
                        principal.CName = user.CName;
                        string roles = user.Roles;
                        principal.Roles = roles.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToList();
                        principal.BusinessUnitID = user.BusinessUnitID;
                        //  principal.AuthorizedBusinessUnitID = srvAuthorize.GetAuthorizedBU(principal.UserID, principal.BusinessUnitID);
                        string userData = CWPrincipal.GetCookieUserData(principal);
                        DateTime expirationDate = DateTime.Now.Add(FormsAuthentication.Timeout);
                        string userName = principal.UserName;
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, expirationDate, false, userData);
                        string cookieValue = FormsAuthentication.Encrypt(ticket);

                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue);
                        cookie.Path = FormsAuthentication.FormsCookiePath;
                        cookie.HttpOnly = true;
                        Response.Cookies.Add(cookie);
                    }

                    accessTokenCookie.Expires = DateTime.Now.AddDays(-1);
                    HttpContext.Current.Response.Cookies.Add(accessTokenCookie);
                }
            }
        }

        void Application_PostRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (Context.User != null && Context.User.Identity.IsAuthenticated)
            {
                return;
            }
            if (cookie != null && !string.IsNullOrWhiteSpace(cookie.Value))
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
                string userData = ticket.UserData;
                CWPrincipal principal = CWPrincipal.CreatePrincipalFromCookieData(userData);
                Context.User = principal;
            }

        }



        //protected void Application_AcquireRequestState(Object sender, EventArgs e)
        //{
        //    if (Context.User != null && Context.User.Identity.IsAuthenticated)
        //    {
        //        FormsIdentity identity = (FormsIdentity)Context.User.Identity;
        //        if (identity == null)
        //        {
        //            return;
        //        }
        //        FormsAuthenticationTicket ticket = identity.Ticket;
        //        string userData = ticket.UserData;
        //        CWPrincipal principal = CWPrincipal.CreatePrincipalFromCookieData(userData);
        //        Context.User = principal;
        //        //HttpCookie cookie = HttpContext.Current.Request.Cookies[ConstantString.COOKIE_ROLE_NAME];
        //        //Context.User = new GenericPrincipal(Context.User.Identity, roles.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries));  // One role

        //    }
        //}
    }
}
